package com.example.apache_shiro.config;


import com.example.apache_shiro.entity.User;
import com.example.apache_shiro.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

//自定义的Realm  extends AuthorizingRealm
public class UserRealm  extends AuthorizingRealm {

    @Autowired
    UserService userService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了授权");
       SimpleAuthorizationInfo info= new SimpleAuthorizationInfo();
       //info.addStringPermission("user:add");
       //拿到当前登录的这个对象
        Subject subject=SecurityUtils.getSubject();
        String perms= String.valueOf(subject.getPrincipal());//拿到user的数据
        //设置当前用户的权限
        info.addStringPermission(perms);
        return info;
    }
    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //连接真实的数据库
        UsernamePasswordToken userToken=(UsernamePasswordToken)token;
        //获取用户输入的用户名
        String username=userToken.getUsername();
        //检测用户是否存在
        List<User> user= userService.queryUserByName(username);
        Subject current=SecurityUtils.getSubject();
        Session session=current.getSession();
        session.setAttribute("loginUser",user.size());
        if(user.size()==0){//没有这个人
            return null;
        }
        //比较密码是否正确
        return new SimpleAuthenticationInfo(user.get(0).getPerms(),user.get(0).getPwd(),"");
    }
}
